package com.ashley.phonemsn

import android.Manifest
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Bundle
import android.telephony.SmsManager
import android.telephony.SmsMessage
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Send
import androidx.compose.material.icons.filled.SwapHoriz
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.PersonSearch
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.semantics.Role
import androidx.compose.foundation.clickable
import androidx.compose.ui.text.input.ImeAction
import androidx.core.app.ActivityCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.ashley.phonemsn.ui.theme.PhoneMSNTheme

class SmsFragment : Fragment() {
    private val SMS_PERMISSION_REQUEST_CODE = 1001

    private val viewModel: SmsViewModel by viewModels()
    
    // 联系人选择回调
    private var onContactSelectedCallback: ((String) -> Unit)? = null

    // SMS发送状态广播接收器
    private val sentSmsReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val messageId = intent?.getIntExtra("message_id", -1)
            android.util.Log.d(
                "SmsFragment",
                "收到发送状态广播，resultCode: $resultCode, messageId: $messageId"
            )
            when (resultCode) {
                android.app.Activity.RESULT_OK -> {
                    Toast.makeText(context, "短信发送成功", Toast.LENGTH_SHORT).show()
                }

                else -> {
                    val errorMessage = when (resultCode) {
                        SmsManager.RESULT_ERROR_GENERIC_FAILURE -> "发送失败: 一般错误"
                        SmsManager.RESULT_ERROR_RADIO_OFF -> "发送失败: 无线电关闭"
                        SmsManager.RESULT_ERROR_NULL_PDU -> "发送失败: 空PDU"
                        SmsManager.RESULT_ERROR_NO_SERVICE -> "发送失败: 无服务"
                        17 -> "发送失败: 消息格式错误或内容被运营商拦截"
                        32 -> "发送失败: 操作被禁止，请检查权限设置或设备策略"
                        else -> "短信发送失败，错误码: $resultCode"
                    }
                    Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    // SMS送达状态广播接收器
    private val deliveredSmsReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val messageId = intent?.getIntExtra("message_id", -1)
            android.util.Log.d(
                "SmsFragment",
                "收到送达状态广播，resultCode: $resultCode, messageId: $messageId"
            )
            if (resultCode == android.app.Activity.RESULT_OK) {
                Toast.makeText(context, "短信已送达", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(context, "短信送达失败", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private val smsReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            android.util.Log.d("SmsFragment", "收到广播: ${intent?.action}")

            if (intent?.action == "android.provider.Telephony.SMS_RECEIVED") {
                val bundle = intent.extras
                if (bundle != null) {
                    try {
                        val pdus = bundle["pdus"] as? Array<Any>
                        android.util.Log.d("SmsFragment", "PDUs数量: ${pdus?.size ?: 0}")

                        if (pdus != null && pdus.isNotEmpty()) {
                            val fullMessageBuilder = StringBuilder()
                            var senderAddress: String? = null

                            for (pdu in pdus) {
                                try {
                                    val smsMessage =
                                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                            val format = bundle.getString("format")
                                            SmsMessage.createFromPdu(pdu as ByteArray, format)
                                        } else {
                                            SmsMessage.createFromPdu(pdu as ByteArray)
                                        }

                                    if (senderAddress == null) {
                                        senderAddress = smsMessage.originatingAddress
                                        senderAddress =
                                            senderAddress?.replace("[^0-9]".toRegex(), "")
                                    }

                                    fullMessageBuilder.append(smsMessage.messageBody)
                                } catch (e: Exception) {
                                    android.util.Log.e(
                                        "SmsFragment",
                                        "处理短信片段失败: ${e.message}",
                                        e
                                    )
                                }
                            }

                            val fullMessage = fullMessageBuilder.toString()
                            android.util.Log.d(
                                "SmsFragment",
                                "完整短信内容: $fullMessage, 发送者: $senderAddress"
                            )

                            if (senderAddress != null && fullMessage.isNotEmpty()) {
                                activity?.runOnUiThread {
                                    val messageId = viewModel.getNewMessageId()
                                    val newMessage = Message(
                                        messageId,
                                        fullMessage,
                                        false,
                                        getCurrentTime(),
                                        senderAddress
                                    )

                                    viewModel.addMessage(newMessage)
                                    android.util.Log.d(
                                        "SmsFragment",
                                        "接收到的短信已添加到列表: $fullMessage"
                                    )

//                                    if (senderAddress != viewModel.currentPhoneNumber.value) {
//                                        Toast.makeText(context, "收到来自 $senderAddress 的新消息", Toast.LENGTH_SHORT).show()
//                                    }
                                }
                            }
                        }
                    } catch (e: Exception) {
                        android.util.Log.e("SmsFragment", "解析短信失败: ${e.message}", e)
                    }
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 注册ActivityResultLauncher
        startContactActivityForResult = registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()
        ) { result ->
            if (result.resultCode == android.app.Activity.RESULT_OK) {
                val phoneNumber = result.data?.getStringExtra(ContactActivity.EXTRA_PHONE_NUMBER)
                val contactName = result.data?.getStringExtra(ContactActivity.EXTRA_CONTACT_NAME)
                phoneNumber?.let {
                    onContactSelected(it, contactName)
                }
            }
        }
        
        // 定义所有需要的广播过滤器
        val sentFilter = IntentFilter("SENT_SMS_ACTION")
        val deliveredFilter = IntentFilter("DELIVERED_SMS_ACTION")
        val receiveFilter = IntentFilter("android.provider.Telephony.SMS_RECEIVED")
        receiveFilter.priority = 999
        val smsInterceptFilter = IntentFilter(SmsInterceptService.ACTION_SMS_INTERCEPTED)
        
        // 注册所有广播接收器
        registerReceiverWithCompatibility(sentSmsReceiver, sentFilter, false)
        registerReceiverWithCompatibility(deliveredSmsReceiver, deliveredFilter, false)
        registerReceiverWithCompatibility(smsReceiver, receiveFilter, true)
        registerReceiverWithCompatibility(smsInterceptReceiver, smsInterceptFilter, false)
        
        requestSmsPermission()
        
        // 默认启用短信拦截服务
        SmsInterceptService.startService(requireContext())

        android.util.Log.d("SmsFragment", "广播接收器注册完成")
    }

    /**
     * 兼容不同 Android 版本的广播接收器注册方法
     * @param receiver 广播接收器
     * @param filter 意图过滤器
     * @param exported 是否需要导出（true：可以接收外部广播；false：仅应用内部使用）
     */
    private fun registerReceiverWithCompatibility(
        receiver: BroadcastReceiver,
        filter: IntentFilter,
        exported: Boolean
    ) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            // Android 14+ 必须明确指定导出行为
            val flags = if (exported) {
                Context.RECEIVER_EXPORTED
            } else {
                Context.RECEIVER_NOT_EXPORTED
            }
            requireActivity().registerReceiver(receiver, filter, flags)
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // Android 8.0-13
            requireActivity().registerReceiver(receiver, filter)
        } else {
            // Android 8.0 以下
            requireActivity().registerReceiver(receiver, filter)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return ComposeView(requireContext()).apply {
            setContent {
                PhoneMSNTheme {
                    // 直接使用 Fragment 中的 viewModel 实例
                    val currentPhoneNumber by viewModel.currentPhoneNumber.collectAsState()
                    val currentMessages by viewModel.currentMessages.collectAsState()

                    SmsChatScreen(
        phoneNumber = currentPhoneNumber,
        messages = currentMessages,
        savedPhoneNumbers = viewModel.savedPhoneNumbers.collectAsState().value,
        onSendMessage = { content ->
            sendSms(content)
        },
        onUpdatePhoneNumber = { number ->
            viewModel.updatePhoneNumber(number)
        },
        onDeletePhoneNumber = { number ->
            viewModel.deletePhoneNumber(number)
        },
        fragment = this@SmsFragment
    )
                }
            }
        }
    }

    // 短信拦截广播接收器
    private val smsInterceptReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent?.action == SmsInterceptService.ACTION_SMS_INTERCEPTED) {
                val senderAddress = intent.getStringExtra(SmsInterceptService.EXTRA_SENDER_ADDRESS)
                val messageContent =
                    intent.getStringExtra(SmsInterceptService.EXTRA_MESSAGE_CONTENT)
                val timestamp = intent.getLongExtra(SmsInterceptService.EXTRA_TIMESTAMP, 0L)

                android.util.Log.d(
                    "SmsFragment",
                    "收到拦截短信广播 - 发送者: $senderAddress, 内容: $messageContent"
                )

                // 将拦截的短信添加到消息列表
                if (senderAddress != null && messageContent != null) {
                    activity?.runOnUiThread {
                        val messageId = viewModel.getNewMessageId()
                        val newMessage = Message(
                            messageId,
                            messageContent,
                            false,
                            getCurrentTime(),
                            senderAddress
                        )
                        viewModel.addMessage(newMessage)
                        android.util.Log.d("SmsFragment", "拦截的短信已添加到列表: $messageContent")
                    }
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        // 注销所有广播接收器
        try {
            requireActivity().unregisterReceiver(sentSmsReceiver)
            requireActivity().unregisterReceiver(deliveredSmsReceiver)
            requireActivity().unregisterReceiver(smsReceiver)
            requireActivity().unregisterReceiver(smsInterceptReceiver)
        } catch (e: IllegalArgumentException) {
            android.util.Log.d("SmsFragment", "接收器已注销或未注册")
        }
    }

    private fun requestSmsPermission() {
        val permissions = arrayOf(
            Manifest.permission.SEND_SMS,
            Manifest.permission.RECEIVE_SMS,
            Manifest.permission.READ_SMS
        )

        val missingPermissions = permissions.filter {
            ActivityCompat.checkSelfPermission(
                requireContext(),
                it
            ) != android.content.pm.PackageManager.PERMISSION_GRANTED
        }

        if (missingPermissions.isNotEmpty()) {
            ActivityCompat.requestPermissions(
                requireActivity(),
                missingPermissions.toTypedArray(),
                SMS_PERMISSION_REQUEST_CODE
            )
            android.util.Log.d("SmsFragment", "请求缺少的权限: $missingPermissions")
        } else {
            android.util.Log.d("SmsFragment", "已拥有所有短信相关权限")
        }
    }

    private fun sendSms(content: String) {
        val phoneNumber = viewModel.currentPhoneNumber.value
        if (content.isEmpty() || phoneNumber.isEmpty()) {
            Toast.makeText(requireContext(), "请输入有效的手机号和短信内容", Toast.LENGTH_SHORT)
                .show()
            return
        }

        // 检查所有必要的短信权限
        val requiredPermissions = arrayOf(
            Manifest.permission.SEND_SMS
        )
        
        // 检查是否有缺失的权限
        val missingPermissions = requiredPermissions.filter {
            ActivityCompat.checkSelfPermission(requireContext(), it) != 
            android.content.pm.PackageManager.PERMISSION_GRANTED
        }
        
        if (missingPermissions.isNotEmpty()) {
            android.util.Log.d("SmsFragment", "缺失的权限: $missingPermissions")
            Toast.makeText(requireContext(), "没有发送短信的权限，请重新授予权限", Toast.LENGTH_SHORT).show()
            // 立即请求权限，而不是等待用户再次点击发送
            ActivityCompat.requestPermissions(
                requireActivity(),
                missingPermissions.toTypedArray(),
                SMS_PERMISSION_REQUEST_CODE
            )
            return
        }

        try {
            val messageId = viewModel.getNewMessageId()

            val sentMessageIntent = Intent("SENT_SMS_ACTION").apply {
                putExtra("message_id", messageId)
            }

            val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                android.app.PendingIntent.FLAG_UPDATE_CURRENT or android.app.PendingIntent.FLAG_MUTABLE
            } else {
                android.app.PendingIntent.FLAG_UPDATE_CURRENT
            }

            val sentPI = android.app.PendingIntent.getBroadcast(
                requireContext(),
                messageId,
                sentMessageIntent,
                flags
            )

            val smsManager = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                requireContext().getSystemService(SmsManager::class.java)
                    ?: throw IllegalStateException("无法获取SmsManager")
            } else {
                SmsManager.getDefault()
            }

            android.util.Log.d("SmsFragment", "准备发送短信到: $phoneNumber, 内容: $content")

            // 立即添加到消息列表
            viewModel.addMessage(
                Message(
                    messageId,
                    content,
                    true,
                    getCurrentTime(),
                    null
                )
            )

            if (content.length > 160) {
                val parts = smsManager.divideMessage(content)
                val sentPis = ArrayList<android.app.PendingIntent>()

                for (i in parts.indices) {
                    val partRequestCode = messageId + i
                    val partSentPI = android.app.PendingIntent.getBroadcast(
                        requireContext(),
                        partRequestCode,
                        sentMessageIntent,
                        flags
                    )
                    sentPis.add(partSentPI)
                }

                smsManager.sendMultipartTextMessage(
                    phoneNumber,
                    null,
                    parts,
                    sentPis,
                    null
                )
            } else {
                smsManager.sendTextMessage(
                    phoneNumber,
                    null,
                    content,
                    sentPI,
                    null
                )
            }

        } catch (e: Exception) {
            android.util.Log.e("SmsFragment", "发送短信异常", e)
            Toast.makeText(requireContext(), "发送失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        if (requestCode == SMS_PERMISSION_REQUEST_CODE) {
            val grantedPermissions = mutableListOf<String>()
            val deniedPermissions = mutableListOf<String>()

            for (i in permissions.indices) {
                if (grantResults[i] == android.content.pm.PackageManager.PERMISSION_GRANTED) {
                    grantedPermissions.add(permissions[i])
                } else {
                    deniedPermissions.add(permissions[i])
                }
            }

            android.util.Log.d("SmsFragment", "授予的权限: $grantedPermissions")
            android.util.Log.d("SmsFragment", "拒绝的权限: $deniedPermissions")

            if (deniedPermissions.isNotEmpty()) {
                Toast.makeText(
                    requireContext(),
                    "部分权限被拒绝，可能影响短信功能",
                    Toast.LENGTH_LONG
                ).show()
            } else if (grantedPermissions.isNotEmpty() && grantedPermissions.contains(Manifest.permission.SEND_SMS)) {
                // 所有权限都已授予，特别是SEND_SMS权限
                Toast.makeText(
                    requireContext(),
                    "权限已授予，可以发送短信",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }

    private fun getCurrentTime(): String {
        val calendar = java.util.Calendar.getInstance()
        val hour = calendar.get(java.util.Calendar.HOUR_OF_DAY).toString().padStart(2, '0')
        val minute = calendar.get(java.util.Calendar.MINUTE).toString().padStart(2, '0')
        return "$hour:$minute"
    }
    
    // 设置联系人选择回调
    fun setOnContactSelectedCallback(callback: (String) -> Unit) {
        this.onContactSelectedCallback = callback
    }

    // 处理选择的联系人
    fun onContactSelected(phoneNumber: String, contactName: String? = null) {
        if (onContactSelectedCallback != null) {
            onContactSelectedCallback!!(phoneNumber)
        } else {
            // 如果没有设置回调，则更新ViewModel中的电话号码和联系人名称
            viewModel.updatePhoneNumber(phoneNumber, contactName)
        }
    }
    
    // 提供ViewModel的公共方法
    fun provideViewModel(): SmsViewModel {
        return viewModel
    }
    
    // 添加启动ContactActivity的结果监听器
    // 联系人选择ActivityResultLauncher
    // 启动联系人选择Activity的公共方法
    fun launchContactActivity() {
        val intent = Intent(requireContext(), ContactActivity::class.java)
        startContactActivityForResult.launch(intent)
    }
    
    private lateinit var startContactActivityForResult: ActivityResultLauncher<Intent>

}

@Composable
fun SmsChatScreen(
    phoneNumber: String,
    messages: List<Message>,
    savedPhoneNumbers: Set<String>,
    onSendMessage: (String) -> Unit,
    onUpdatePhoneNumber: (String) -> Unit,
    onDeletePhoneNumber: (String) -> Unit,
    fragment: Fragment
) {
    // 从ViewModel获取电话号码和联系人名称，确保UI与ViewModel状态同步
    val smsFragment = fragment as SmsFragment
    // 使用provideViewModel方法访问viewModel
    val viewModel = smsFragment.provideViewModel()
    // 直接委托访问ViewModel的电话号码状态
    val currentPhoneNumber by viewModel.currentPhoneNumber.collectAsState()
    // 直接委托访问ViewModel的联系人名称状态
    val currentContactName by viewModel.currentContactName.collectAsState()
    
    var inputMessage by remember { mutableStateOf("") }
    var showPhoneNumberSelector by remember { mutableStateOf(false) }
    var showAddContactDialog by remember { mutableStateOf(false) }
    val listState = rememberLazyListState()

    LaunchedEffect(messages.size) {
        if (messages.isNotEmpty()) {
            listState.animateScrollToItem(messages.size - 1)
        }
    }

    Column(modifier = Modifier.fillMaxSize()) {
        ContactHeader(
            phoneNumber = currentPhoneNumber,
            contactName = currentContactName,
            fragment = fragment
        )

        LazyColumn(
            modifier = Modifier.weight(1f),
            state = listState,
            contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp)
        ) {
            items(messages) { message ->
                MessageBubble(message = message)
                Spacer(modifier = Modifier.height(8.dp))
            }
        }

        InputArea(
            message = inputMessage,
            onMessageChange = { inputMessage = it },
            onSend = {
                if (inputMessage.trim().isNotEmpty()) {
                    onSendMessage(inputMessage.trim())
                    inputMessage = ""
                }
            }
        )
    }

    
    
    // 电话号码选择器对话框
    if (showPhoneNumberSelector) {
        PhoneNumberSelectorDialog(
            currentNumber = phoneNumber,
            savedNumbers = savedPhoneNumbers,
            onSelectNumber = {
                onUpdatePhoneNumber(it)
                showPhoneNumberSelector = false
            },
            onDeleteNumber = onDeletePhoneNumber,
            onAddNewNumber = {
                showPhoneNumberSelector = false
                showAddContactDialog = true
            },
            onDismiss = { showPhoneNumberSelector = false }
        )
    }
}

@Composable
fun ContactHeader(
    phoneNumber: String,
    contactName: String,
    fragment: Fragment
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .background(MaterialTheme.colorScheme.primary)
            .padding(start = 12.dp, end = 15.dp, top = 12.dp, bottom = 12.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Box(
            modifier = Modifier
                .size(40.dp)
                .clip(CircleShape)
                .background(Color.White)
                .padding(8.dp)
        ) {
            Text(
                text = contactName.take(1),
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colorScheme.primary,
                textAlign = TextAlign.Center,
                modifier = Modifier.align(Alignment.Center)
            )
        }

        Spacer(modifier = Modifier.width(12.dp))

        Column(modifier = Modifier.weight(1f)) {
            Text(
                text = contactName,
                color = Color.White,
                fontSize = 16.sp,
                fontWeight = FontWeight.Medium
            )
            Text(
                text = phoneNumber,
                color = Color(0xCCFFFFFF),
                fontSize = 12.sp
            )

            // 短信拦截状态显示（默认已启用）
            Text(
                text = "短信拦截: 已启用",
                color = Color(0xFF4CAF50),
                fontSize = 10.sp
            )
        }

        // 将按钮放在最右侧 - 通讯录入口
        IconButton(onClick = {
            // 启动ContactActivity
            (fragment as SmsFragment).launchContactActivity()
        }) {
            Icon(
                imageVector = Icons.Default.PersonSearch,
                contentDescription = "通讯录选择",
                tint = Color.White
            )
        }
    }
}


@Composable
fun MessageBubble(message: Message) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = if (message.isSent) Arrangement.End else Arrangement.Start
    ) {
        if (!message.isSent) {
            Spacer(modifier = Modifier.width(44.dp))
        }

        Column(modifier = Modifier.widthIn(max = 280.dp)) {
            Box(
                modifier = Modifier
                    .background(
                        color = if (message.isSent) MaterialTheme.colorScheme.primary else Color.LightGray,
                        shape = RoundedCornerShape(18.dp)
                    )
                    .padding(12.dp)
            ) {
                Text(
                    text = message.content,
                    color = if (message.isSent) Color.White else Color.Black
                )
            }

            Text(
                text = message.timestamp,
                fontSize = 10.sp,
                color = Color.Gray,
                modifier = Modifier
                    .padding(top = 4.dp)
                    .align(if (message.isSent) Alignment.End else Alignment.Start)
            )
        }
    }
}

@Composable
fun InputArea(
    message: String,
    onMessageChange: (String) -> Unit,
    onSend: () -> Unit
) {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .background(Color.White)
            .padding(8.dp)
    ) {
        Row(verticalAlignment = Alignment.Bottom) {
            OutlinedTextField(
                value = message,
                onValueChange = onMessageChange,
                placeholder = { Text(text = "输入短信内容...") },
                modifier = Modifier
                    .weight(1f)
                    .heightIn(min = 40.dp, max = 120.dp),
                shape = RoundedCornerShape(20.dp),
                singleLine = false
            )

            Spacer(modifier = Modifier.width(8.dp))

            Button(
                onClick = onSend,
                enabled = message.trim().isNotEmpty(),
                modifier = Modifier
                    .size(40.dp)
                    .clip(CircleShape),
                shape = CircleShape,
                contentPadding = PaddingValues(0.dp)
            ) {
                Icon(
                    imageVector = Icons.Filled.Send,
                    contentDescription = "发送",
                    modifier = Modifier.size(20.dp)
                )
            }
        }
    }
}

@Composable
fun ContactInfoDialog(
    phoneNumber: String,
    onUpdatePhoneNumber: (String) -> Unit,
    onDismiss: () -> Unit
) {
    var newPhoneNumber by rememberSaveable { mutableStateOf(phoneNumber) }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text(text = "联系人信息") },
        text = {
            Column {
                Text(text = "修改联系人号码：")
                Spacer(modifier = Modifier.height(8.dp))
                OutlinedTextField(
                    value = newPhoneNumber,
                    onValueChange = { newValue -> newPhoneNumber = newValue },
                    placeholder = { Text("请输入电话号码") },
                    modifier = Modifier.fillMaxWidth()
                )
            }
        },
        confirmButton = {
            Button(onClick = {
                onUpdatePhoneNumber(newPhoneNumber)
                onDismiss()
            }) {
                Text(text = "确定")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text(text = "取消")
            }
        }
    )
}

@Composable
fun AddContactDialog(
    onAddContact: (String) -> Unit,
    onDismiss: () -> Unit
) {
    var newPhoneNumber by remember { mutableStateOf("") }
    var errorMessage by remember { mutableStateOf("") }
    
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text(text = "添加新联系人") },
        text = {
            Column {
                TextField(
                    value = newPhoneNumber,
                    onValueChange = {
                        // 只允许输入数字
                        if (it.all { char -> char.isDigit() || char == '+' } || it.isEmpty()) {
                            newPhoneNumber = it
                            // 清除错误消息
                            if (errorMessage.isNotEmpty()) {
                                errorMessage = ""
                            }
                        }
                    },
                    label = { Text(text = "请输入电话号码") },
                    placeholder = { Text(text = "例如: 10086") },

                    modifier = Modifier.fillMaxWidth()
                )
                if (errorMessage.isNotEmpty()) {
                    Text(
                        text = errorMessage,
                        color = MaterialTheme.colorScheme.error,
                        fontSize = 12.sp,
                        modifier = Modifier.padding(top = 4.dp)
                    )
                }
            }
        },
        confirmButton = {
            Button(onClick = {
                val trimmedNumber = newPhoneNumber.trim()
                if (trimmedNumber.isEmpty()) {
                    errorMessage = "请输入电话号码"
                } else if (trimmedNumber.length < 5) {
                    errorMessage = "电话号码太短"
                } else {
                    onAddContact(trimmedNumber)
                }
            }) {
                Text(text = "添加")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text(text = "取消")
            }
        }
    )
}

@Composable
fun PhoneNumberSelectorDialog(
    currentNumber: String,
    savedNumbers: Set<String>,
    onSelectNumber: (String) -> Unit,
    onDeleteNumber: (String) -> Unit,
    onAddNewNumber: () -> Unit,
    onDismiss: () -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text(text = "选择或添加联系人") },
        text = {
            Column(modifier = Modifier.heightIn(max = 300.dp)) {
                Text(text = "已保存的联系人：", modifier = Modifier.padding(bottom = 8.dp))
                LazyColumn(modifier = Modifier.fillMaxWidth()) {
                    items(savedNumbers.toList()) { number ->
                        Row(
                            modifier = Modifier
                            .fillMaxWidth()
                            .padding(8.dp)
                            .clickable(
                                onClick = {
                                    if (number != currentNumber) {
                                        onSelectNumber(number)
                                    }
                                }
                            ),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            RadioButton(
                                selected = number == currentNumber,
                                onClick = { if (number != currentNumber) onSelectNumber(number) }
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                            Text(
                                text = if (number == "10086") "中国移动客服 ($number)" else number,
                                modifier = Modifier.weight(1f)
                            )
                            if (savedNumbers.size > 1) {
                                IconButton(
                                    onClick = { onDeleteNumber(number) },
                                    modifier = Modifier.size(24.dp)
                                ) {
                                    Icon(
                                        imageVector = Icons.Filled.Delete,
                                        contentDescription = "删除联系人",
                                        tint = MaterialTheme.colorScheme.error
                                    )
                                }
                            }
                        }
                    }
                }
            }
        },
        confirmButton = {
            Button(onClick = onAddNewNumber) {
                Text(text = "添加新联系人")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text(text = "取消")
            }
        }
    )
}